package com.example.healthapp.utils;

import android.Manifest;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import androidx.core.app.ActivityCompat;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

// 工具类
public class InterfaceTool {
    
    /**
     * 权限检测与申请
     *
     * @param activity
     * @param permissions
     */
    public static void requestPermissions(Activity activity, String[] permissions) {
        for (int i = 0; i < permissions.length; i++) {
            if (activity.checkSelfPermission(permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(activity, permissions, 1);
            }
        }
    }

    //属性
    public static NfcUtils nfcUtils;

    /**
     * 界面转跳
     *
     * @param c
     * @param cls
     */
    public static void setIntent(Context c, Class cls) {
        Intent intent = new Intent(c, cls);
        c.startActivity(intent);
    }

    /**
     * 回调接口
     */
    public interface MyCallback {
        default void getData(HashMap<String, Object> hashMap) {
        }
    }

    //函数

    /**
     * 判断有无网络
     */
    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    /**
     * 沉浸式
     */
    public static void setFullScreen(Activity activity, boolean isLightStatusBar) {
        Window window = activity.getWindow();
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = window.getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
            int ui = decorView.getSystemUiVisibility();
            if (isLightStatusBar) {
                ui |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR; // 设置为浅色状态栏
            } else {
                ui &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR; // 设置为深色状态栏
            }
            decorView.setSystemUiVisibility(ui);
            decorView.setElevation(5);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= 19)
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
    }

    /**
     * 根据传入的long返回日期String
     */
    public static String getDate(long date) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        return simpleDateFormat.format(new Date(date));
    }

    /**
     * 封装动画
     */
    public static void setAnimator(View view, float[] translationX, float[] translationY, float[] scaleX, float[] scaleY, float[] alpha, float[] rotation, long during, int loop, float pivotX) {
        ObjectAnimator tX = ObjectAnimator.ofFloat(view, "translationX", translationX);
        tX.setRepeatCount(loop);
        ObjectAnimator tY = ObjectAnimator.ofFloat(view, "translationY", translationY);
        tY.setRepeatCount(loop);
        ObjectAnimator sX = ObjectAnimator.ofFloat(view, "scaleX", scaleX);
        view.setPivotX(pivotX); // 0f 表示左边缘，1f 表示右边缘，0.5f 表示中间
        sX.setRepeatCount(loop);
        ObjectAnimator sY = ObjectAnimator.ofFloat(view, "scaleY", scaleY);
        sY.setRepeatCount(loop);
        ObjectAnimator aP = ObjectAnimator.ofFloat(view, "alpha", alpha);
        aP.setRepeatCount(loop);
        ObjectAnimator rT = ObjectAnimator.ofFloat(view, "rotation", rotation);
        rT.setRepeatCount(loop);
        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.play(tX).with(tY).with(sX).with(sY).with(aP).with(rT);
        animatorSet.setDuration(during);
        animatorSet.start();
    }

    public static void setAnimator(View view, float[] translationX, float[] translationY, float[] scaleX, float[] scaleY, float[] alpha, float[] rotation, long during, int loop) {
        ObjectAnimator tX = ObjectAnimator.ofFloat(view, "translationX", translationX);
        tX.setRepeatCount(loop);
        ObjectAnimator tY = ObjectAnimator.ofFloat(view, "translationY", translationY);
        tY.setRepeatCount(loop);
        ObjectAnimator sX = ObjectAnimator.ofFloat(view, "scaleX", scaleX);
        sX.setRepeatCount(loop);
        ObjectAnimator sY = ObjectAnimator.ofFloat(view, "scaleY", scaleY);
        sY.setRepeatCount(loop);
        ObjectAnimator aP = ObjectAnimator.ofFloat(view, "alpha", alpha);
        aP.setRepeatCount(loop);
        ObjectAnimator rT = ObjectAnimator.ofFloat(view, "rotation", rotation);
        rT.setRepeatCount(loop);
        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.play(tX).with(tY).with(sX).with(sY).with(aP).with(rT);
        animatorSet.setDuration(during);
        animatorSet.start();
    }

    //通用GET请求
    public static Response generalGETOkHttp(String url) {
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        Request request = new Request.Builder().url(url).method("GET", null).build();
        try {
            Response response = client.newCall(request).execute();
            return response;
        } catch (IOException e) {
            e.printStackTrace();
            Log.d("phcc", "generalOkHttp: 请求失败");
            return null;
        }
    }

    //获取公网ip
    public static JSONObject getPublicNetWorkIP() {
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        Request request = new Request.Builder().url("http://ip-api.com/json/").method("GET", null).addHeader("User-Agent", "apifox/1.0.0 (https://www.apifox.cn)").build();
        try {
            Response response = client.newCall(request).execute();
            return new JSONObject(response.body().string());
        } catch (IOException | JSONException e) {
            e.printStackTrace();
            Log.d("phcc", "获取公网ip错误" + e);
            return null;
        }
    }

    //获得网络图片
    public static Bitmap generalOkHttpBitmap(String bitmapUrl) {
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        Request request = new Request.Builder().url(bitmapUrl).method("GET", null).build();
        try {
            Response response = client.newCall(request).execute();
            return BitmapFactory.decodeStream(response.body().byteStream());
        } catch (IOException e) {
            e.printStackTrace();
            Log.d("phcc", "网络图片请求失败");
            return null;
        }
    }

    //base64转bitmap
    public static Bitmap getBitmapOfBase64(String base64) {
        byte[] bytes = Base64.decode(base64, Base64.DEFAULT);
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    }

    //bitmap转base64
    public static String getBase64OfBitmap(Bitmap bitmap) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 20, outputStream);
        String base = Base64.encodeToString(outputStream.toByteArray(), Base64.DEFAULT);
        try {
            outputStream.reset();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return base;
    }

    //阿帕奇bitmap转base64
//    public static String getBase64OfBitmapApaches(Bitmap bitmap){
//        ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
//        bitmap.compress(Bitmap.CompressFormat.PNG,10,outputStream);
//        String base= org.apaches.commons.codec.binary.Base64.encodeBase64String(outputStream.toByteArray());
//        try {
//            outputStream.reset();
//            outputStream.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return base;
//    }

    //base64转byte[]
    public static byte[] getByteOfBase64(String base64) {
        return Base64.decode(base64, Base64.DEFAULT);
    }

    //byte[]转base64
    public static String getBase64OfByte(byte[] bytes) {
        return Base64.encodeToString(bytes, Base64.DEFAULT);
    }

    //转跳到权限设置页面
    public static void intoPermissionSetting(Context context) {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + context.getPackageName()));
        context.startActivity(intent);
    }

    /**
     * 获取SN
     *
     * @return
     */
    public static String getSN() {
        String serial = "";
        //通过android.os获取sn号
        try {
            serial = Build.SERIAL;
            if (!serial.equals("") && !serial.equals("unknown")) return serial;
        } catch (Exception e) {
            serial = "";
        }

        //通过反射获取sn号
        try {
            Class<?> c = Class.forName("android.os.SystemProperties");
            Method get = c.getMethod("get", String.class);
            serial = (String) get.invoke(c, "ro.serialno");
            if (!serial.equals("") && !serial.equals("unknown")) return serial;

            //9.0及以上无法获取到sn，此方法为补充，能够获取到多数高版本手机 sn
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) serial = Build.getSerial();
        } catch (Exception e) {
            serial = "";
        }
        return serial;
    }

    //获得设备android_ID
    public static String getDeviceID(Context context) {
        String androidId = Settings.System.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        return androidId;
    }

    //获得ip地址
    public static String getIpAddressString() {
        try {
            for (Enumeration<NetworkInterface> enNetI = NetworkInterface.getNetworkInterfaces(); enNetI.hasMoreElements(); ) {
                NetworkInterface netI = enNetI.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = netI.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (inetAddress instanceof Inet4Address && !inetAddress.isLoopbackAddress()) {
                        return inetAddress.getHostAddress();
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return "0.0.0.0";
    }

    // 获取有限网IP
    private static String getLocalIp() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                        return inetAddress.getHostAddress();
                    }
                }
            }
        } catch (SocketException ex) {
        }
        return "0.0.0.0";
    }

    //获取手机号
    public static String getPhoneNumber(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE);
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_NUMBERS) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            return "无权限";
        }
        return telephonyManager.getLine1Number();
    }

    //获得手机型号
    public static String getPhoneModel() {
        return Build.MODEL;
    }

    //设备名称
    public static String getDeviceName() {
        return Build.DEVICE;
    }

    //设备版本
    public static String getBuildId() {
        return Build.ID;
    }

    //获得IMEI
    public static String getPhoneIMEI(Context context) {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            return "android 10.0及以上无法获得IMEI";
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            return tm.getImei();
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return tm.getDeviceId();
        } else return tm.getDeviceId();
    }

    /**
     * 获取当前app version code
     */
    public static long getAppVersionCode(Context context) {
        long appVersionCode = 0;
        try {
            PackageInfo packageInfo = context.getApplicationContext().getPackageManager().getPackageInfo(context.getPackageName(), 0);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                appVersionCode = packageInfo.getLongVersionCode();
            } else {
                appVersionCode = packageInfo.versionCode;
            }
        } catch (PackageManager.NameNotFoundException e) {
            Log.e("", e.getMessage());
        }
        return appVersionCode;
    }

    /**
     * 获取当前app version name
     */
    public static String getAppVersionName(Context context) {
        String appVersionName = "";
        try {
            PackageInfo packageInfo = context.getApplicationContext().getPackageManager().getPackageInfo(context.getPackageName(), 0);
            appVersionName = packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            Log.e("", e.getMessage());
        }
        return appVersionName;
    }

    /**
     * 【nfc】
     */
    public static class NfcUtils {
        //nfc
        public NfcAdapter mNfcAdapter;
        public IntentFilter[] mIntentFilter = null;
        public PendingIntent mPendingIntent = null;
        public String[][] mTechList = null;

        /**
         * 构造函数，用于初始化nfc
         */
        public NfcUtils(Activity activity) {
            mNfcAdapter = NfcCheck(activity);
            NfcInit(activity);
        }

        /**
         * 检查NFC是否打开
         */
        public NfcAdapter NfcCheck(Activity activity) {
            NfcAdapter mNfcAdapter = NfcAdapter.getDefaultAdapter(activity);
            if (mNfcAdapter == null) {
                return null;
            } else {
                if (!mNfcAdapter.isEnabled()) {
                    Intent setNfc = new Intent(Settings.ACTION_NFC_SETTINGS);
                    activity.startActivity(setNfc);
                }
            }
            return mNfcAdapter;
        }

        /**
         * 初始化nfc设置
         */
        public void NfcInit(Activity activity) {
            mPendingIntent = PendingIntent.getActivity(activity, 0, new Intent(activity, activity.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), PendingIntent.FLAG_IMMUTABLE);
            IntentFilter filter = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
            IntentFilter filter2 = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
            try {
                filter.addDataType("*/*");
            } catch (IntentFilter.MalformedMimeTypeException e) {
                e.printStackTrace();
            }
            mIntentFilter = new IntentFilter[]{filter, filter2};
            mTechList = null;
        }

        /**
         * 读取NFC的数据
         */
        public String readNFCFromTag(Intent intent) throws UnsupportedEncodingException {
            if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
                Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
                String cardId = ByteArrayToHexString(tagFromIntent.getId());
                return cardId;
            }
            return "";
        }

        /**
         * 将字节数组转换为字符串
         */
        public String ByteArrayToHexString(byte[] inarray) {
            int i, j, in;
            String[] hex = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"};
            String out = "";
            for (j = 0; j < inarray.length; ++j) {
                in = (int) inarray[j] & 0xff;
                i = (in >> 4) & 0x0f;
                out += hex[i];
                i = in & 0x0f;
                out += hex[i];
            }
            return out;
        }

        /**
         * 读取nfcID
         */
        public String readNFCId(Intent intent) throws UnsupportedEncodingException {
            Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            String id = ByteArrayToHexString(tag.getId());
            return id;
        }

        /**
         * 往nfc写入数据
         */
        public void writeNFCToTag(String data, Intent intent) throws IOException, FormatException {
            Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            Ndef ndef = Ndef.get(tag);
            ndef.connect();
            NdefRecord ndefRecord = NdefRecord.createTextRecord(null, data);
            NdefRecord[] records = {ndefRecord};
            NdefMessage ndefMessage = new NdefMessage(records);
            ndef.writeNdefMessage(ndefMessage);
        }
    }

    /**
     * 图片压缩
     */
    public static Bitmap bitmapCompression(Bitmap bitmap, int inSampleSize) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        //质量压缩
        bitmap.compress(Bitmap.CompressFormat.JPEG, 50, outputStream);
        byte[] bytes1 = outputStream.toByteArray();
        //采样压缩
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.RGB_565;//建议使用
        options.inSampleSize = inSampleSize;   //采样率
        Bitmap bitmap1 = BitmapFactory.decodeByteArray(bytes1, 0, bytes1.length, options);
        //释放资源
        try {
            outputStream.reset();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap1;
    }

    public static Bitmap bitmapCompression(byte[] bytes, int inSampleSize) {
        //采样压缩
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.RGB_565;//建议使用
        options.inSampleSize = inSampleSize;   //采样率
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
    }
}